package com.ontheroad.controller;

import cn.modoumama.page.GridDataModel;
import com.ontheroad.core.annotation.QiniuUploadToken;
import com.ontheroad.core.util.SpringSecurityUtils;
import com.ontheroad.core.web.BaseController;
import com.ontheroad.system.entity.SysUser;
import com.ontheroad.system.service.SysUserService;
import com.ontheroad.topic.model.TopicModel;
import com.ontheroad.topic.service.TopicService;
import com.ontheroad.user.model.UserModel;
import com.ontheroad.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by Administrator on 2017/10/27.
 */
@Controller
@RequestMapping("topic")
public class TopicController extends BaseController {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private TopicService topicService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserService userService;

    @RequestMapping("init")
    public String init() {
        return "topic/init";
    }

    @RequestMapping("getData")
    @ResponseBody
    public GridDataModel getData(HttpServletRequest request) {
        GridDataModel model = getGridData(request, topicService);
        try {
            if (model.getRows() != null && model.getRows().size() > 0) {
                List<TopicModel> list = (List<TopicModel>) model.getRows();
                List<Integer> createIdsSys = new ArrayList<>();
                List<Integer> createIdsUser = new ArrayList<>();
                Integer type;
                for (TopicModel topicModel : list) {
                    if (topicModel != null) {
                        type = topicModel.getType();
                        if (type == 1) {
                            // 系统管理员创建
                            createIdsSys.add(topicModel.getCreateId());
                        } else if (type == 2) {
                            // 手机端用户创建
                            createIdsUser.add(topicModel.getCreateId());
                        }
                    }
                }
                Map<Integer, SysUser> sysUserMap = new HashMap<>();
                if (createIdsSys.size() > 0) {
                    List<SysUser> sysUsers = sysUserService.findByIds(createIdsSys);
                    for (SysUser sysUser : sysUsers) {
                        sysUserMap.put(sysUser.getUserId().intValue(), sysUser);
                    }
                }
                Map<Integer, UserModel> userModelMap = new HashMap<>();
                if (createIdsUser.size() > 0) {
                    List<UserModel> userModels = userService.findByIds(createIdsUser);
                    for (UserModel user : userModels) {
                        userModelMap.put(user.getId(), user);
                    }
                }
                SysUser sysUser;
                UserModel user;
                for (TopicModel topicModel : list) {
                    if (topicModel.getType() == 1) {
                        // 系统管理员创建
                        sysUser = sysUserMap.get(topicModel.getCreateId());
                        topicModel.setNick(sysUser.getUserName());
                    } else if (topicModel.getType() == 2) {
                        // 手机端用户创建
                        user = userModelMap.get(topicModel.getCreateId());
                        topicModel.setNick(user.getNick());
                    }
                }
                model.setRows(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("设置昵称出错");
        }
        return model;
    }

    @QiniuUploadToken
    @RequestMapping("toAdd")
    public String toAdd(Map map) {
        return "topic/add";
    }

    @RequestMapping("save")
    public String save(TopicModel topicModel, Map map) {
        try {
            topicModel.setCreateTime(new Date());
            topicModel.setType(1);
            SysUser user = SpringSecurityUtils.getCurrentUser();
            topicModel.setCreateId(user.getUserId().intValue());
            topicService.insert(topicModel);
        } catch (Exception e) {
            log.error("保存话题出错：", e);
            map.put("optionResult", 2);
            map.put("faildMessage", "保存活动类型出错");
        }
        return SUCCESS;
    }

    @QiniuUploadToken
    @RequestMapping("edit")
    public String edit(Integer id, Map map) {
        TopicModel topicModel = topicService.findById(id);
        if (topicModel == null) {
            return FAILD;
        }
        map.put("model", topicModel);
        return "topic/edit";
    }

    @RequestMapping("update")
    public String update(TopicModel topicModel, Map map) {
        try {
            topicService.updateById(topicModel);
        } catch (Exception e) {
            log.error("更新话题出错：", e);
            map.put("optionResult", 2);
            map.put("faildMessage", "更新活动类型出错");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "delete")
    public void delete(HttpServletRequest request, PrintWriter out) {
        log.debug("method: delete() ");
        String msg = "操作成功";
        boolean result = true;
        try {
            String ids = request.getParameter("ids");
            String[] aDeleteId = ids.split(",");
            for (String id : aDeleteId) {
                topicService.removeById(Integer.valueOf(id));
            }
        } catch (Exception e) {
            msg = "系统发生异常！";
            result = false;
        }
        ajaxJsonResponse(out, result, msg);
    }

    @RequestMapping("setHot")
    public void setHot(HttpServletRequest request, PrintWriter out) {
        String msg = "操作成功";
        boolean result = true;
        try {
            String ids = request.getParameter("ids");
            String[] hotIds = ids.split(",");
            for (String id : hotIds) {
                topicService.updateHotByIds(Integer.valueOf(id));
            }
        } catch (Exception e) {
            msg = "系统发生异常！";
            result = false;
        }
        ajaxJsonResponse(out, result, msg);
    }

}
